import request from '../../utils/request.js'
// pages/detail/detail.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsDetail: {},
    isCollect: false
  },
  goodsInfo: {},
  goodsId: '',
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.goodsId = options.goods_id
    console.log(options)
    this.getGoodsDetail()
  },

  async getGoodsDetail() {
    const res = await request({
      url: '/goods/detail?goods_id=' + this.goodsId
    })
    this.goodsInfo = res.data.message
    let goodsDetail = {
      pics: res.data.message.pics,
      name: res.data.message.goods_name,
      introduce: res.data.message.goods_introduce,
      price: res.data.message.goods_price
    }
    let collect = wx.getStorageSync('collect') || []
    let isCollect = collect.some(
      (item) => item.goods_id === this.goodsInfo.goods_id
    )
    this.setData({
      goodsDetail,
      isCollect
    })
    //console.log(this.data.goodsDetail)
  },

  handlePreviewImage(e) {
    console.log(e)
    let url = e.currentTarget.dataset.url
    let urls = this.data.goodsDetail.pics.map((item) => {
      return item.pics_mid
    })
    console.log(urls)
    wx.previewImage({
      current: url,
      urls: urls
    })
  },

  onClickCart() {
    wx.switchTab({
      url: '../shopcart/shopcart'
    })
  },

  addCart() {
    let cart = wx.getStorageSync('shopcart') || []
    //console.log(cart);
    let index = cart.findIndex((item) => {
      return item.goods_id === this.goodsInfo.goods_id
    })
    if (index == -1) {
      this.goodsInfo.num = 1
      cart.push(this.goodsInfo)
    } else {
      cart[index].num++
    }
    wx.setStorageSync('shopcart', cart)
    wx.showToast({
      title: '添加成功'
    })
  },

  onClickStar() {
    let collect = wx.getStorageSync('collect') || []
    let index = collect.findIndex((item) => {
      return item.goods_id === this.goodsInfo.goods_id
    })
    console.log(index)
    if (index == -1) {
      collect.push(this.goodsInfo)
      wx.showToast({
        title: '收藏成功'
      })
      this.setData({
        isCollect: true
      })
    } else {
      collect.splice(index, 1)
      wx.showToast({
        title: '取消收藏成功'
      })
      this.setData({
        isCollect: false
      })
    }
    wx.setStorageSync('collect', collect)
  }
})